import React, { useEffect, useImperativeHandle } from "react";
import { Form } from "antd";
import { useDispatch, useSelector } from "react-redux";
import { Dispatch, RootState } from "@/store";

interface commonForm {
  data?: any;
}
const CommonForm = (props: commonForm, ref: React.Ref<unknown> | undefined) => {
  const dispatch = useDispatch<Dispatch>();
  const { modalConfig, flowData } = useSelector(
    (state: RootState) => state.diagram
  );
  const [form] = Form.useForm();

  const initialValues = flowData?.get(modalConfig?.nodeId) || {};

  const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 18 },
  };

  useImperativeHandle(ref, () => ({
    // 将 submit 方法暴露给父组件
    submit: () => {
      return form
        .validateFields()
        .then((values) => {
          dispatch.diagram.saveFlowNode({
            id: modalConfig?.nodeId,
            ...values,
            data: {
              ...values,
            },
          });
        })
        .catch((err) => {
          return false;
        });
    },
  }));

  useEffect(() => {
    form.resetFields();
  }, [modalConfig?.nodeId, form]);

  return (
    <Form {...layout} form={form} initialValues={initialValues}>
      <Form.Item
        label="名称"
        name="label"
        rules={[{ required: true, message: "节点名称不能为空" }]}
      >
        <textarea placeholder="请输入节点名称" maxLength={600} />
      </Form.Item>
      <Form.Item label="描述" name="remark">
        <textarea placeholder="请输入节点的描述信息" />
      </Form.Item>
    </Form>
  );
};

export default React.forwardRef(CommonForm);
